<?php
class Recommendation_Random extends Recommendation{
	
	public function __construct(){
		parent::__construct();
		$this->method_recommendation= RECOMMANDATION_ALEATOIRE;
	}
	
	protected function makeQuery(){
		// http://akinas.com/pages/en/blog/mysql_random_row/
		
		//$id_user_clause= isset($_SESSION['infosAuth']) && (!empty($_SESSION['infosAuth'])) ? "id_title NOT IN (SELECT id_title FROM Rating WHERE id_user='".$_SESSION['infosAuth']->getIdUser()."') AND" : ""; 
		//$id_user_clause = isset($_SESSION['infosAuth']) && (!empty($_SESSION['infosAuth'])) ? "LEFT JOIN Rating ON Title.id_title = Rating.id_title WHERE id_user='".$_SESSION['infosAuth']->getIdUser()."' AND Rating.id_title IS NULL" : "";

/* SELECT * FROM Title LEFT JOIN Rating ON Title.id_title=Rating.id_title AND Rating.id_user=13 WHERE Rating.id_title is NULL */

		$id_user_clause= isset($_SESSION['infosAuth']) && (!empty($_SESSION['infosAuth'])) ? "LEFT JOIN Rating ON Title.id_title=Rating.id_title AND Rating.id_user='".$_SESSION['infosAuth']->getIdUser()."' WHERE Rating.id_title is NULL " : "";
		
		/* Prérequete */
		$query = "SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM Title ".$id_user_clause;
		
		$db = Outils_Bd::getInstance()->getConnexion();
		$sth=$db->prepare($query);
		$sth->execute();
		$offset = $sth->fetch(PDO::FETCH_ASSOC);

		$requete = "SELECT Title.id_title, Title.name, Title.artist, Title.youtube_id FROM Title ".$id_user_clause." LIMIT ".$offset['offset'].", 1"; 
		
		// Méthode suivante : ne fonctionne pas vraiment :
		//$requete = "SELECT * FROM Title WHERE id_title >= (SELECT FLOOR( MAX(id_title) * RAND()) FROM Title ) AND id_title NOT IN (SELECT id_title FROM Rating WHERE id_user='{$id_user}') AND youtube_id IS NOT null ORDER BY id_title LIMIT 1"; 
		
		
		//"SELECT * FROM Title WHERE id_title NOT IN (SELECT id_title FROM Rating WHERE id_user='{$this->id_user}') AND youtube_id IS NOT null";
		
		return $requete;
	}
	
	public static function canBeInstanciate(){
		return true;	
	}
	
	public function getMethodRecommendation(){
		return $this->method_recommendation;
	}
	
}
?>